package com.gxa.accommodation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.accommodation.dto.AccommodationRoomTypeDTO;
import com.gxa.accommodation.entity.AccommodationRoomType;
import com.gxa.accommodation.mapper.AccommodationRoomTypeMapper;
import com.gxa.accommodation.service.AccommodationRoomTypeService;
import com.gxa.accommodation.vo.AccommodationRoomTypeVO;
import com.gxa.common.base.RespResult;
import com.gxa.common.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AccommodationRoomTypeServiceImpl
        extends ServiceImpl<AccommodationRoomTypeMapper, AccommodationRoomType>
        implements AccommodationRoomTypeService {

    @Autowired
    private AccommodationRoomTypeMapper roomTypeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //缓存key
    private  static final String FIND_ROOM_TYPE="findAccommodationRoomType";


    /**
     * 添加房间类型
     * @param accommodationRoomTypeDTO 房间类型实体DTO
     * @return RespResult
     */
    @Override
    public RespResult addRoomType(AccommodationRoomTypeDTO accommodationRoomTypeDTO) {
        AccommodationRoomType roomType = BeanUtil.copyProperties(accommodationRoomTypeDTO, AccommodationRoomType.class);

        //判断该房间类型信息是否已经存在
        LambdaQueryWrapper<AccommodationRoomType> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AccommodationRoomType::getRoomArea,roomType.getRoomArea())
                .eq(AccommodationRoomType::getRoomPrice,roomType.getRoomPrice())
                .eq(AccommodationRoomType::getRoomTypeName,roomType.getRoomTypeName())
                .eq(AccommodationRoomType::getSeatingCapacity,roomType.getSeatingCapacity());

        //返回已经存在的房间类型列表，若已经存在就在房间数量上加1
        List<AccommodationRoomType> roomTypes = roomTypeMapper.selectList(queryWrapper);
        if (roomTypes.size()>0){
            roomTypeMapper.updateCountById(roomTypes.get(0).getId());
            return RespResult.success("id:"+roomTypes.get(0).getId()+"==该房间类型已经存在，房间类型数量加一");
        }

        //房间类型不存在，添加一个新的房间类型
        int result = roomTypeMapper.insert(roomType);
        if (result>0){
            redisTemplate.delete(FIND_ROOM_TYPE);
            return RespResult.success("id:"+roomType.getId()+"添加房间类型成功");
        }

        return RespResult.error("添加成功");

    }

    /**
     * 添加图片
     * @param file
     * @param id
     * @param request
     * @return
     */
    @Override
    public RespResult addRoomTypeImg(MultipartFile file, Long id, HttpServletRequest request) {
        try{
            String imgUrl = FileUtils.saveImage(file, request, FileUtils.ROOM_TYPE);

            FileUtils.deleteFile(imgUrl);
            AccommodationRoomType accommodationRoomType=new AccommodationRoomType();
            accommodationRoomType.setId(id);
            accommodationRoomType.setRoomImg(imgUrl);

            roomTypeMapper.updateById(accommodationRoomType);
            redisTemplate.delete(FIND_ROOM_TYPE);
            return RespResult.success("添加图片成功");
        }catch (Exception e){
            e.printStackTrace();
            return RespResult.error("添加失败");
        }

    }


    @Override
    public RespResult showRoomTypeList(Integer currentPage, Integer pageSize) {
        if (currentPage==null||pageSize==null||currentPage<=0||pageSize<=0){
            currentPage=1;
            pageSize=10;
        }
        Page<AccommodationRoomTypeVO> voPage=null;

        ValueOperations valueOperations = redisTemplate.opsForValue();

        redisTemplate.setHashKeySerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        //从Redis获取到page
        voPage = (Page<AccommodationRoomTypeVO>) valueOperations.get(FIND_ROOM_TYPE);

        if (voPage!=null&&currentPage==1){
            log.info("从redis中读取房间类型列表");
            return RespResult.success(voPage);
        }else {
            Page<AccommodationRoomTypeVO> page=new Page<>(currentPage,pageSize);
            voPage= roomTypeMapper.selectByPage(page);
            if (currentPage>1){
                return RespResult.success(voPage);
            }else {
                //存入缓存
                valueOperations.set(FIND_ROOM_TYPE,voPage,5, TimeUnit.MINUTES);
                return RespResult.success(voPage);
            }


        }


    }

    /**
     * 修改房间类型
     * @param accommodationRoomTypeDTO
     * @return
     */
    @Override
    public RespResult updateRoomType(AccommodationRoomTypeDTO accommodationRoomTypeDTO) {
        AccommodationRoomType accommodationRoomType = BeanUtil.copyProperties(accommodationRoomTypeDTO, AccommodationRoomType.class);
        roomTypeMapper.updateById(accommodationRoomType);
        redisTemplate.delete(FIND_ROOM_TYPE);
        return RespResult.success("修改成功");
    }

    /**
     * 修改房间类型状态
     * @param id
     * @param roomStatus
     * @return
     */
    @Override
    public RespResult updateRoomStatusById(Long id, Byte roomStatus) {
        if (id!=null&&roomStatus!=null){
            roomTypeMapper.updateRoomStatusById(id,roomStatus);
            redisTemplate.delete(FIND_ROOM_TYPE);
            return RespResult.success("修改房间状态成功");
        }
        return RespResult.error("修改失败");

    }


    /**
     * 根据id删除房间类型
     * @param id
     * @return
     */
    @Override
    public RespResult delRoomTypeById(Long id) {
        if (id!=null){
            Integer count = roomTypeMapper.countRoomTypeByRoomTypeId(id);
            if (count==0){
                roomTypeMapper.deleteById(id);
                redisTemplate.delete(FIND_ROOM_TYPE);
                return RespResult.success("删除成功");
            }else {
                return RespResult.error("该房间类型下还有房间不能下架");
            }

        }
        return RespResult.error("删除失败");
    }
}
